package com.tica.it.itmanage.config.jwt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.tica.catool.common.Result;
import com.tica.catool.exception.BusinessException;
import com.tica.catool.exception.ExceptionCode;
import com.tica.catool.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.Filter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.function.BiConsumer;


/**
 * jwt过滤器
 */
@Slf4j
@Component
public class ShiroJwtFilter extends BasicHttpAuthenticationFilter implements Filter {


    /**
     * 判断是否携带了有效的JwtToken
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("==isAccessAllowed==");
        return executeLogin(request, response);
    }

    /**
     * 执行登录
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        log.info("==executeLogin==");

        try {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String token = httpServletRequest.getHeader(JwtUtil.HEADER);
            ShiroJwtToken jwtToken = new ShiroJwtToken(token);
            // 提交给realm进行登入，如果错误他会抛出异常并被捕获
            getSubject(request, response).login(jwtToken);
            return true;
        } catch (AuthenticationException e) {
            HttpServletResponse res = (HttpServletResponse) response;
            Throwable throwable = e.getCause();
            if (throwable instanceof TokenExpiredException) {
                renderString(res, JSON.toJSONString(Result.fail(10001, "token过期"), SerializerFeature.WriteMapNullValue));
            } else {
                renderString(res, JSON.toJSONString(Result.fail(10001, "token非法"), SerializerFeature.WriteMapNullValue));
            }
        }

        return false;

    }

    /**
     * 认证失败时，自定义返回json数据
     *
     * @param request  请求
     * @param response 响应
     * @return boolean* @throws Exception 异常
     */
//    @Override
//    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//        Result result = Result.fail(-1, "认证失败");
//        Object parse = JSONObject.toJSON(result);
//        response.setCharacterEncoding("utf-8");
//        response.getWriter().print(parse);
//        return super.onAccessDenied(request, response);
//    }


    /**
     * 对跨域提供支持
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * @param response
     * @param body
     */
    public void renderString(HttpServletResponse response, String body) {

        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(body);
        } catch (IOException e) {
            log.error("response error.", e);
        }
    }

}

